package com.yht.weblog.web.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.yht.weblog.common.domain.dos.ArticleDO;
import com.yht.weblog.common.domain.mapper.ArticleMapper;
import com.yht.weblog.common.utils.PageResponse;
import com.yht.weblog.common.utils.Response;
import com.yht.weblog.web.convert.ArticleConvert;
import com.yht.weblog.web.model.vo.archive.FindArchiveArticlePageListReqVO;
import com.yht.weblog.web.model.vo.archive.FindArchiveArticlePageListRspVO;
import com.yht.weblog.web.model.vo.archive.FindArchiveArticleRspVO;
import com.yht.weblog.web.service.ArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.YearMonth;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author: yht
 * @date: 2024/1/21 9:30
 * @description:
 **/
@Service
public class ArchiveServiceImpl implements ArchiveService {

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 前台获取归档文章列表
     *
     * @param findArchiveArticlePageListReqVO 请求参数对象
     * @return 响应对象
     */
    @Override
    public Response findArchiveArticlePageList(FindArchiveArticlePageListReqVO findArchiveArticlePageListReqVO) {
        Long current = findArchiveArticlePageListReqVO.getCurrent();
        Long size = findArchiveArticlePageListReqVO.getSize();

        // 调用数据库操作层的方法获取归档文章列表
        IPage<ArticleDO> articleDOPage = articleMapper.selectPageList(current, size, null, null, null);
        List<ArticleDO> articleDOS = articleDOPage.getRecords();


        List<FindArchiveArticlePageListRspVO> vos = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(articleDOS)) {
            // 将 DO 类型的对象转换成 VO 类型的对象
            List<FindArchiveArticleRspVO> archiveArticleRspVOS = articleDOS.stream()
                    .map(articleDO -> ArticleConvert.INSTANCE.convertDO2ArchiveArticleVO(articleDO))
                    .collect(Collectors.toList());

            // 按照创建月份分组
            Map<YearMonth, List<FindArchiveArticleRspVO>> map = archiveArticleRspVOS.stream().collect(Collectors.groupingBy(FindArchiveArticleRspVO::getCreateMonth));
            Map<YearMonth, List<FindArchiveArticleRspVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(map);

            // 将分组后的数据放入 rspVO 中
            sortedMap.forEach((k, v) -> {
                FindArchiveArticlePageListRspVO rspVO = FindArchiveArticlePageListRspVO.builder()
                        .month(k)
                        .articles(v)
                        .build();
                vos.add(rspVO);
            });
        }
        // 返回成功响应
        return PageResponse.success(articleDOPage, vos);
    }

}
